<?php
namespace Models;

class PostModel extends CommonModel {
    public function add($data) {
        $sql = 'insert into posts (cate_id, title, content, user_id) values (:cate_id, :title, :content, :user_id)';
        $stmt = $this->db->prepare($sql);
        $stmt->bindValue(':cate_id', $data['cate_id']);
        $stmt->bindValue(':title', $data['title']);
        $stmt->bindValue(':content', $data['content']);
        $stmt->bindValue(':user_id', $data['user_id']);
        return $stmt->execute();
    }


    public function getPostList($where, $limit) {
        $sql = 'select posts.id, posts.title as p_title, posts.content, posts.created_at, posts.praise_count, posts.step_count,
                users.username, categories.title as c_title from posts left join users on users.id = posts.user_id 
                left join categories on categories.id = posts.cate_id';
        if ($where) $sql .= $where;
        $sql .= ' order by posts.id desc';
        $sql .= $limit;
        return $this->db->query($sql)->fetchAll();
    }

    public function getPostCount($where) {
        $sql = 'select count(id) as count from posts';
        if ($where) $sql .= $where;
        return $this->db->query($sql)->fetch()['count'];
    }

    public function evaluate($type, $post_id) {
        if ($type == 1) {
            $sql = 'update posts set praise_count = praise_count + 1 where id = ' . $post_id;
        } else {
            $sql = 'update posts set step_count = step_count + 1 where id = ' . $post_id;
        }
        return $this->db->exec($sql);
    }

    public function getPostById($post_id) {
        $sql = 'select * from posts where id = ' . $post_id;
        return $this->db->query($sql)->fetch();
    }

    public function getHotPosts() {
        $sql = 'select id, title, praise_count, step_count from posts order by praise_count desc, step_count desc, id desc limit 10';
        return $this->db->query($sql)->fetchAll();
    }
}